<template>
  <div class="panel-tab__content">
    <el-table :data="elementListenersList" size="mini" border>
      <el-table-column label="序号" width="50px" type="index"/>
      <el-table-column label="事件类型" min-width="80px" show-overflow-tooltip :formatter="row => listenerEventTypeObject[row.event]"/>
      <el-table-column label="监听类型" min-width="80px" show-overflow-tooltip
                       :formatter="row => listenerTypeObject[row.listenerType]"/>
      <el-table-column label="操作" width="100px">
        <template slot-scope="{ row, $index }">
          <el-button size="mini" type="text" @click="openListenerForm(row, $index)">编辑</el-button>
          <el-button size="mini" type="text" style="color: #ff4d4f" @click="removeListener(row, $index)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="element-drawer__button">
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="openCustomListener(null)">添加内置监听</el-button>
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="openListenerForm(null)">添加自定义监听</el-button>
    </div>

    <!-- 监听器 编辑/创建 部分 -->
    <el-drawer class="c-f-d-panel-drawer" :visible.sync="listenerFormModelVisible" title="执行监听" :size="`${width}px`" :modal-append-to-body="false" append-to-body destroy-on-close>
      <el-form :model="listenerForm" label-width="96px" ref="listenerFormRef"
               @submit.native.prevent>
        <el-form-item label="事件类型" prop="event" :rules="{ required: true, message: '请选择事件类型', trigger: ['blur', 'change'] }">
          <el-select v-model="listenerForm.event" clearable>
            <el-option label="开始" value="start"/>
            <el-option label="结束" value="end"/>
            <el-option label="启用" value="take"/>
          </el-select>
        </el-form-item>
        <el-form-item label="监听类型" prop="listenerType" :rules="{ required: true, message: '请选择监听类型', trigger: ['blur', 'change'] }">
          <el-select v-model="listenerForm.listenerType" clearable>
            <el-option v-for="i in Object.keys(listenerTypeObject)" :key="i" :label="listenerTypeObject[i]" :value="i"/>
          </el-select>
        </el-form-item>
        <el-form-item
            v-if="listenerForm.listenerType === 'classListener'"
            label="Java类"
            prop="class"
            key="listener-class"
            :rules="{ required: true, message: '请输入Java类', trigger: ['blur', 'change'] }"
        >
          <el-input v-model="listenerForm.class" clearable></el-input>
        </el-form-item>
        <el-form-item
            v-if="listenerForm.listenerType === 'expressionListener'"
            label="表达式"
            prop="expression"
            key="listener-expression"
            :rules="{ required: true, message: '请输入表达式', trigger: ['blur', 'change'] }"
        >
          <el-input v-model="listenerForm.expression" clearable></el-input>
        </el-form-item>
        <el-form-item
            v-if="listenerForm.listenerType === 'delegateExpressionListener'"
            label="代理表达式"
            prop="delegateExpression"
            key="listener-delegate"
            :rules="{ required: true, message: '请输入代理表达式', trigger: ['blur', 'change'] }"
        >
          <el-input v-model="listenerForm.delegateExpression" clearable></el-input>
        </el-form-item>
      </el-form>
      <el-divider/>
      <p class="listener-filed__title">
        <span><i class="el-icon-menu"></i>注入字段：</span>
        <el-button size="mini" type="primary" @click="openListenerFieldForm(null)">添加字段</el-button>
      </p>
      <el-table :data="fieldsListOfListener" size="mini" max-height="240" border fit style="flex: none">
        <el-table-column label="序号" width="50px" type="index"/>
        <el-table-column label="字段名称" min-width="100px" prop="name"/>
        <el-table-column label="字段类型" min-width="80px" show-overflow-tooltip
                         :formatter="row => fieldTypeObject[row.fieldType]"/>
        <el-table-column label="字段值/表达式" min-width="100px" show-overflow-tooltip
                         :formatter="row => row.string || row.expression"/>
        <el-table-column label="操作" width="100px">
          <template slot-scope="{ row, $index }">
            <el-button size="mini" type="text" @click="openListenerFieldForm(row, $index)">编辑</el-button>
            <el-button size="mini" type="text" style="color: #ff4d4f" @click="removeListenerField(row, $index)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="element-drawer__button">
        <el-button @click="listenerFormModelVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveListenerConfig">保 存</el-button>
      </div>
    </el-drawer>

    <!-- 注入字段 编辑/创建 部分 -->
    <el-dialog class="c-f-d-dialog" title="字段配置" :visible.sync="listenerFieldFormModelVisible" width="600px" :modal-append-to-body="false" append-to-body destroy-on-close>
      <el-form :model="listenerFieldForm" label-width="96px" ref="listenerFieldFormRef"
               style="height: 136px" @submit.native.prevent>
        <el-form-item label="字段名称" prop="name" :rules="{ required: true, message: '请输入字段名称', trigger: ['blur', 'change'] }">
          <el-input v-model="listenerFieldForm.name" clearable/>
        </el-form-item>
        <el-form-item label="字段类型" prop="fieldType" :rules="{ required: true, message: '请输入字段类型',  trigger: ['blur', 'change'] }">
          <el-select v-model="listenerFieldForm.fieldType">
            <el-option v-for="i in Object.keys(fieldTypeObject)" :key="i" :label="fieldTypeObject[i]" :value="i"/>
          </el-select>
        </el-form-item>
        <el-form-item
            v-if="listenerFieldForm.fieldType === 'string'"
            label="字段值"
            prop="string"
            key="field-string"
            :rules="{ required: true, message: '请输入字段值', trigger: ['blur', 'change'] }"
        >
          <el-input v-model="listenerFieldForm.string" clearable/>
        </el-form-item>
        <el-form-item
            v-if="listenerFieldForm.fieldType === 'expression'"
            label="表达式"
            prop="expression"
            key="field-expression"
            :rules="{ required: true, message: '请输入表达式', trigger: ['blur', 'change'] }"
        >
          <el-input v-model="listenerFieldForm.expression" clearable/>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="listenerFieldFormModelVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveListenerFiled">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog class="c-f-d-dialog c-f-d-dialog__listener" title="内置监听器" :visible.sync="listenerCustomModelVisible" width="800px" :modal-append-to-body="false" append-to-body destroy-on-close>
      <el-form :model="customListenerForm" ref="customListenerFormRef" label-width="96px" label-position="top" @submit.native.prevent>
        <el-form-item label="事件类型" prop="event" :rules="{ required: true, message: '请选择事件类型', trigger: ['blur', 'change'] }">
          <el-select v-model="customListenerForm.event" clearable>
            <el-option v-for="i in Object.keys(listenerEventTypeObject)" :key="i" :label="listenerEventTypeObject[i]" :value="i" />
          </el-select>
        </el-form-item>
        <el-form-item label="监听器" prop="listenerType" :rules="{ required: true, message: '请选择监听器', trigger: 'change' }">
          <el-table ref="customListenerTable" :data="listeners" size="mini" highlight-current-row border @current-change="handleCustomListenerRowSelect">
            <el-table-column width="50">
              <template slot-scope="{row}">
                <el-radio class="radio" v-model="customListenerForm.id" :label="row.id">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column label="序号" width="50px" type="index" />
            <el-table-column label="监听类型" prop="type" width="120px" show-overflow-tooltip :formatter="row => listenerTypeObject[row.type]" />
            <el-table-column label="名称" prop="name" min-width="80px" show-overflow-tooltip />
            <el-table-column label="值" prop="value" min-width="80px" show-overflow-tooltip />
            <el-table-column label="操作" width="100px">
              <template slot-scope="{ row }">
                <el-popover
                    placement="right"
                    width="400"
                    trigger="hover">
                  <el-table :data="row.params || []">
                    <el-table-column min-width="100" property="type" label="参数类型" :formatter="row => fieldTypeObject[row.type]"></el-table-column>
                    <el-table-column min-width="100" property="name" label="参数名"></el-table-column>
                    <el-table-column min-width="100" property="value" label="参数值"></el-table-column>
                  </el-table>
                  <el-button slot="reference" size="mini" type="text">查看参数</el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>

      <template slot="footer">
        <el-button @click="listenerCustomModelVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCustomListenerConfig">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {createListenerObject, updateElementExtensions} from "../../util/utils";
import {eventType, fieldType, initCustomListener, initListenerForm, initListenerType, listenerType} from "./utilSelf";

export default {
  name: "ElementListeners",
  props: {
    id: String,
    type: String,
    // 内置监听
    listeners: {
      type: Array,
      default() {
        return [];
      }
    },
  },
  inject: {
    prefix: "prefix",
    width: "width"
  },
  data() {
    return {
      elementListenersList: [], // 监听器列表
      listenerForm: {}, // 监听器详情表单
      listenerFormModelVisible: false, // 监听器 编辑 侧边栏显示状态
      customListenerForm: {event: "", listenerType: ""}, // 内置监听
      listenerCustomModelVisible: false,
      fieldsListOfListener: [],
      listenerFieldForm: {}, // 监听器 注入字段 详情表单
      listenerFieldFormModelVisible: false, // 监听器 注入字段表单弹窗 显示状态
      editingListenerIndex: -1, // 监听器所在下标，-1 为新增
      editingListenerFieldIndex: -1, // 字段所在下标，-1 为新增
      listenerEventTypeObject: eventType,
      listenerTypeObject: listenerType,
      fieldTypeObject: fieldType
    };
  },
  watch: {
    id: {
      immediate: true,
      handler(val) {
        val && val.length && this.$nextTick(() => this.resetListenersList());
      }
    }
  },
  methods: {
    // 打开内置监听弹窗
    openCustomListener() {
      this.customListenerForm = {};
      this.listenerCustomModelVisible = true;
    },
    // 内置监听选中
    handleCustomListenerRowSelect(row) {
      const newCustomListenerForm = {category: row.category, type: row.type, name: row.name, value: row.value, params: row.params, id: row.id};
      let customListenerForm = initCustomListener(newCustomListenerForm);
      Object.keys(customListenerForm).forEach(key => {
        this.$set(this.customListenerForm, key, customListenerForm[key]);
      });
      this.$refs["customListenerFormRef"].validateField("listenerType");
    },
    // 保存自定义监听配置
    async saveCustomListenerConfig() {
      this.$refs["customListenerFormRef"].validate(valid => {
        if (valid) {
          const listenerObject = createListenerObject(this.customListenerForm, false, this.prefix);
          if (this.editingListenerIndex === -1) {
            this.bpmnElementListeners.push(listenerObject);
            this.elementListenersList.push(this.customListenerForm);
          } else {
            this.bpmnElementListeners.splice(this.editingListenerIndex, 1, listenerObject);
            this.elementListenersList.splice(this.editingListenerIndex, 1, this.customListenerForm);
          }
          // 保存其他配置
          this.otherExtensionList = this.bpmnElement.businessObject?.extensionElements?.values?.filter(ex => ex.$type !== `${this.prefix}:TaskListener`) ?? [];
          updateElementExtensions(this.bpmnElement, this.otherExtensionList.concat(this.bpmnElementListeners));
          // 4. 隐藏侧边栏
          this.listenerCustomModelVisible = false;
          this.customListenerForm = {};
        }
      });
    },
    resetListenersList() {
      this.bpmnElement = window.bpmnInstances.bpmnElement;
      this.otherExtensionList = [];
      this.bpmnElementListeners =
          this.bpmnElement.businessObject?.extensionElements?.values?.filter(ex => ex.$type === `${this.prefix}:ExecutionListener`) ?? [];
      this.elementListenersList = this.bpmnElementListeners.map(listener => initListenerType(listener));
    },
    // 打开 监听器详情 侧边栏
    openListenerForm(listener, index) {
      if (listener) {
        this.listenerForm = initListenerForm(listener);
        this.editingListenerIndex = index;
      } else {
        this.listenerForm = {};
        this.editingListenerIndex = -1; // 标记为新增
      }
      if (listener && listener.fields) {
        this.fieldsListOfListener = listener.fields.map(field => ({
          ...field,
          fieldType: field.string ? "string" : "expression"
        }));
      } else {
        this.fieldsListOfListener = [];
        this.$set(this.listenerForm, "fields", []);
      }
      // 打开侧边栏并清楚验证状态
      this.listenerFormModelVisible = true;
      this.$nextTick(() => {
        if (this.$refs["listenerFormRef"]) this.$refs["listenerFormRef"].clearValidate();
      });
    },
    // 打开监听器字段编辑弹窗
    openListenerFieldForm(field, index) {
      this.listenerFieldForm = field ? JSON.parse(JSON.stringify(field)) : {};
      this.editingListenerFieldIndex = field ? index : -1;
      this.listenerFieldFormModelVisible = true;
      this.$nextTick(() => {
        if (this.$refs["listenerFieldFormRef"]) this.$refs["listenerFieldFormRef"].clearValidate();
      });
    },
    // 保存监听器注入字段
    saveListenerFiled() {
      this.$refs["listenerFieldFormRef"].validate(valid => {
        if (valid) {
          if (this.editingListenerFieldIndex === -1) {
            this.fieldsListOfListener.push(this.listenerFieldForm);
            this.listenerForm.fields.push(this.listenerFieldForm);
          } else {
            this.fieldsListOfListener.splice(this.editingListenerFieldIndex, 1, this.listenerFieldForm);
            this.listenerForm.fields.splice(this.editingListenerFieldIndex, 1, this.listenerFieldForm);
          }
          this.listenerFieldFormModelVisible = false;
          this.$nextTick(() => (this.listenerFieldForm = {}));
        }
      });
    },
    // 移除监听器字段
    removeListenerField(field, index) {
      this.$confirm("确认移除该字段吗？", "提示", {
        confirmButtonText: "确 认",
        cancelButtonText: "取 消"
      })
          .then(() => {
            this.fieldsListOfListener.splice(index, 1);
            this.listenerForm.fields.splice(index, 1);
          })
          .catch(() => console.info("操作取消"));
    },
    // 移除监听器
    removeListener(listener, index) {
      this.$confirm("确认移除该监听器吗？", "提示", {
        confirmButtonText: "确 认",
        cancelButtonText: "取 消"
      })
          .then(() => {
            this.bpmnElementListeners.splice(index, 1);
            this.elementListenersList.splice(index, 1);
            updateElementExtensions(this.bpmnElement, this.otherExtensionList.concat(this.bpmnElementListeners));
          })
          .catch(() => console.info("操作取消"));
    },
    // 保存监听器配置
    saveListenerConfig() {
      this.$refs["listenerFormRef"].validate(valid => {
        if (valid) {
          const listenerObject = createListenerObject(this.listenerForm, false, this.prefix);
          if (this.editingListenerIndex === -1) {
            this.bpmnElementListeners.push(listenerObject);
            this.elementListenersList.push(this.listenerForm);
          } else {
            this.bpmnElementListeners.splice(this.editingListenerIndex, 1, listenerObject);
            this.elementListenersList.splice(this.editingListenerIndex, 1, this.listenerForm);
          }
          // 保存其他配置
          this.otherExtensionList = this.bpmnElement.businessObject?.extensionElements?.values?.filter(ex => ex.$type !== `${this.prefix}:ExecutionListener`) ?? [];
          updateElementExtensions(this.bpmnElement, this.otherExtensionList.concat(this.bpmnElementListeners));
          // 4. 隐藏侧边栏
          this.listenerFormModelVisible = false;
          this.listenerForm = {};
        }
      });
    }
  }
};
</script>
